import { Component, OnInit } from '@angular/core';
import { GridOptions } from '@ag-grid-community/core';
import { GridConfigService } from '@core/config/grid-config.service';
import { ApiService } from '@core/services/http/api.service';
import { DatePipe } from '@angular/common';
import {ApesMessageService} from "@shared/apes/message";

@Component({
  selector: 'monthly-complaint',
  templateUrl: './monthly-complaint.component.html',
  styles: [`
    boxShowFlex {
      height: 80px;
      display: flex;
      flex-wrap: wrap;

    span {
      width: 100px;
      display: inline-block;
      text-align: right;
      padding-right: 10px;
    }

    boxDiv {
      display: inline-block;
      width: 240px;
    }

    }
  `],
})
export class MonthlyComplaintComponent implements OnInit {
  /** Grid 相关 **/
  rowData: any[] = [];
  resultData: any;
  defaultColDef: any;
  gridOptions: GridOptions;
  pinnedBottomRowData: any[] = [];
  columnDefs: any[] = [];
  height: any = window.innerHeight - 200 + 'px';

  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              private datePipe: DatePipe, private msg: ApesMessageService) {
    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressSizeToFit: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 30,
      rowHeight: 35,
    };
    this.gridOptions.localeText = gridConfigService.getLocaleText();
    this.defaultColDef = {
      width: 125,
      valueFormatter: function(params) {
        return params.value ? params.value : 0;
      },
    };
  }

  ngOnInit() {
    this.getTablesData();

  }


  dealData() {
    let headerObj = {};        // 重新定义头部 数据
    let headerData = [];       // 重新定义头部 数组
    let newData = [];          // 重新定义展示 数组
    let newObj = {};           // 重新定义展示 数据

    //  遍历每一行的数据
    for (let i = 0; i < this.rowData.length; i++) {
      let dept = this.rowData[i]['DEPT_ID'];
      if (!newObj[dept]) {
        newObj[dept] = {};
      }

      let respon = this.rowData[i]['RESPONSIBILITY_COMPLAIN_ID'];   // 区分 责任或非责任客诉
      let categroup = this.rowData[i]['COMPLAIN_CATEGORY_ID'];      // 区分 客诉类型
      //  拼责任、非责任客诉头部 and 数据交互
      if (!headerObj[respon]) {
        headerObj[respon] = {};
        headerObj[respon]['headerName'] = this.rowData[i]['RESPONSIBILITY_COMPLAIN'];
        headerObj[respon]['field'] = respon;
      }
      //  拼客诉类型头部 and 数据交互
      if (!headerObj[respon][categroup]) {
        headerObj[respon][categroup] = {};
        headerObj[respon][categroup]['headerName'] = this.rowData[i]['COMPLAIN_CATEGORY'];
        headerObj[respon][categroup]['field'] = respon + categroup;
      }
      newObj[dept]['DEPT_ID'] = this.rowData[i]['DEPT_ID'];
      newObj[dept]['DEPT_NAME'] = this.rowData[i]['DEPT_NAME'];
      let numId = respon + categroup;       // 每一行对应客诉类型 多少条
      let numSum = respon + '_sum';         // 责任、非责任客诉 合计
      newObj[dept][numId] = this.rowData[i]['NUM'];
      newObj[dept][numSum] = newObj[dept][numSum] ? newObj[dept][numSum] + this.rowData[i]['NUM'] : this.rowData[i]['NUM'];
      // 责任、非责任客诉 总和
      newObj[dept]['sum'] = newObj[dept]['sum'] ? newObj[dept]['sum'] + this.rowData[i]['NUM'] : this.rowData[i]['NUM'];
    }

    //  遍历每一行数据的对象放进 自定义数组
    for (var key in newObj) {
      newData.push(newObj[key]);
    }

    this.rowData = newData;   //  重新将自定义数组赋值给 grid 要传的数组

    //  遍历头部
    for (var key in headerObj) {
      let children = [];
      let data = {};
      for (var key1 in headerObj[key]) {
        if (key1 == 'headerName' || key1 == 'field') {
          data[key1] = headerObj[key][key1];
        } else {
          children.push(headerObj[key][key1]);
        }
      }
      children.push({ 'headerName': '合计', 'field': key + '_sum' });
      data['children'] = children;
      headerData.push(data);
    }

    //  最后交互渲染的数组（grid）
    this.columnDefs = [
      { headerName: '门店', field: 'DEPT_NAME' },
      ...headerData,
      { headerName: '合计', field: 'sum' },
    ];

  }


  getTablesData() {
    let data = { 'DATE': this.datePipe.transform(new Date(), 'yyyy-MM') };
    this.apiService.post('crm.customComplain.queryComplainMonthReport', { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          this.rowData = body;
          if( this.rowData.length === 0 ) {
            this.msg.info(`未找到满足条件的数据`);
          }
          this.dealData();
        } else {
          this.msg.info(body.msg);
        }
      });
  }


}
